import React, { Component } from 'react';
import { Table, Button, Modal, message, Tooltip, Row, Col, Select, Input } from 'antd';
import 'antd/dist/antd.css';
import storeHouse from './StoreHouse.module.css'
import { FormOutlined, DeleteOutlined, EllipsisOutlined, StopOutlined, SettingOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import * as url from '../../util/api';
const { Option } = Select;
const { confirm } = Modal;
export default class StoreHouse extends Component {
    constructor(props) {
        super(props);
        this.state = {
            perSize:5,
            columns: [
                {
                    title: '仓库名称',
                    key: 'repositoryName',
                    align: 'center',
                    render: record => {
                        if (record.flag) {
                            return <div>
                                <span className={storeHouse.storeName}>{record.repositoryName}</span>
                                <span className={storeHouse.defaultName}>默认</span>
                            </div>
                        } else {
                            if (record.repositoryStatus === 0) {
                                return <div>
                                    <span className={[`${storeHouse.storeName}`, `${storeHouse.forbiddenState}`].join(' ')}>{record.repositoryName}</span>
                                </div>
                            } else {
                                return <div>
                                    <span className={storeHouse.storeName}>{record.repositoryName}</span>
                                </div>
                            }

                        }

                    }
                },
                {
                    title: '仓库编码',
                    render: record => {
                        if (record.repositoryStatus === 0) {
                            return <span className={storeHouse.forbiddenState}>{record.repositoryCode}</span>
                        } else {
                            return <span>{record.repositoryCode}</span>
                        }
                    },
                    key: 'repositoryCode',
                    align: 'center'
                },
                {
                    title: '仓库地址',
                    render: record => {
                        if (record.repositoryStatus === 0) {
                            return <span className={storeHouse.forbiddenState}>{record.repositoryAddress}</span>
                        } else {
                            return <span>{record.repositoryAddress}</span>
                        }
                    },
                    key: 'repositoryAddress',
                    align: 'center'
                },
                {
                    title: '状态',
                    key: 'repositoryId',
                    render: record => {
                        if (record.repositoryStatus === 0) {
                            return <span className={storeHouse.forbiddenState}>已禁用</span>
                        } else {
                            return <span>已启用</span>
                        }
                    },
                    align: 'center'
                },
                {
                    title: '',
                    key: 'repositoryId',
                    render: record => {
                        return <div className={storeHouse.operate}>
                            {/* <span>...</span>
                            <div className = {storeHouse.btnBox}>
                                <button>修改</button>
                                <button>禁用</button>
                                <button>删除</button>
                            </div> */}
                            <Tooltip title={() => {
                                return <div className={storeHouse.btnBox}>
                                    {record.flag ? null : <button onClick={() => { this.setDefault(record.repositoryId) }}><SettingOutlined className={storeHouse.operateIcon} />设为默认</button>}
                                    <button onClick={() => { this.editStore(record.repositoryId) }}><FormOutlined className={storeHouse.operateIcon} />修改</button>
                                    <button onClick={() => { this.setForbidden(record.repositoryId) }}><StopOutlined className={storeHouse.operateIcon} /> {record.repositoryStatus?<span>禁用</span>:<span>启用</span>}</button>
                                    <button onClick={() => { this.deleteStore(record.repositoryId) }}><DeleteOutlined className={storeHouse.operateIcon} />删除</button>

                                </div>
                            }} placement="bottom">
                                <span><EllipsisOutlined /></span>
                            </Tooltip>
                            <Modal
                                maskStyle={{ backgroundColor: 'rgba(0,0,0,.15)' }}
                                title={'禁用仓库' + '"' + (this.state.nowStore ? this.state.nowStore : '') + '"'}
                                visible={this.state.isShowForbiddenStore}
                                onOk={this.confirmForbidden}
                                cancelText={'取消'}
                                okText={'确定'}
                                onCancel={this.handleForbiddenCancel}
                            >
                                <p className={storeHouse.ForbiddenDescribe}><ExclamationCircleOutlined className={storeHouse.describeIcon} />禁用该仓库需要为默认发货仓为此仓库的客户重新设置默认发货仓</p>
                                <div className={storeHouse.inputBox}>
                                    <span className={storeHouse.newTips}> <span>*</span>选择仓库</span>
                                    <Select defaultValue="请选择" className={storeHouse.storeSelect} onChange={this.handleSelectChange}>
                                        {this.state.storeData.map(item => <Option key={item.repositoryId} value={item.repositoryId} disabled={this.state.nowId == item.repositoryId ? true : false}>{item.repositoryName}</Option>)}
                                    </Select>
                                </div>
                            </Modal>
                            <Modal
                                maskStyle={{ backgroundColor: 'rgba(0,0,0,.15)' }}
                                title="修改经销商级别"
                                visible={this.state.isShowEditStore}
                                onOk={this.confirmEdit}
                                cancelText={'取消'}
                                okText={'确定'}
                                onCancel={this.handleEditCancel}
                            >
                                <div className={storeHouse.inputBox}>
                                    <span className={storeHouse.newTips}> <span>*</span>仓库名称</span>
                                    <Input className={storeHouse.newStore} name='editName'
                                        value={this.state.editName} onChange={this.handelEditChange} />
                                </div>
                                <div className={storeHouse.inputBox}>
                                    <span className={storeHouse.newTips}> <span>*</span>仓库编号</span>
                                    <Input className={storeHouse.newStore} name='editNum'
                                        value={this.state.editNum} onChange={this.handelEditChange} />
                                </div>
                                <div className={storeHouse.inputBox}>
                                    <span className={storeHouse.newTips}>仓库地址</span>
                                    <Input className={storeHouse.newStore} name='editArea'
                                        value={this.state.editArea} onChange={this.handelEditChange} />
                                </div>
                            </Modal>
                        </div>
                    }

                }
            ]

        }
    }
    getStoreData(currentPage){
        let obj = {
            currentPage:currentPage,
            perSize:this.state.perSize,
        }
        axios({
            url:'/api' + url.queryRepositoryByPage,
            method:'post',
            data:obj
        }).then(res=>{
            console.log(res.data,'获取仓库信息!')
            let arr = res.data.data.repositoryList
            let total = res.data.data.totalCounts
            console.log(total,'总页数')
            this.setState({
                storeData:arr,
                totalPage:total,
                pagination: {
                    position: ['bottomCenter'],
                    defaultCurrent: 1,//默认当前页
                    pageSize:this.state.perSize,//每页条数
                    hideOnSinglePage: true,//只有一页隐藏分页
                    total:total,//数据总数
                    onChange:(currentPage,pageSize)=>{
                        // console.log(currentPage,pageSize,'页码改变了')
                        this.getStoreData(currentPage)
                    }
                }
            })
        })
    }
    componentDidMount(){
        let nowPage = 1
        this.getStoreData(nowPage)
    }
    // 修改仓库
    editStore = (id) => {
        let arr = JSON.parse(JSON.stringify(this.state.storeData))
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].repositoryId === id) {
                this.setState({
                    editName: arr[i].repositoryName,
                    editNum: arr[i].repositoryCode,
                    editArea: arr[i].repositoryAddress,
                    editId:arr[i].repositoryId
                })
            }
        }
        this.setState({
            isShowEditStore: true,
        })
    }
    handelEditChange = (e) => {
        let val = e.target.value.replace(/\s+/g, "")//获取属性值
        let name = e.target.name//获取表单元素的name属性
        this.setState({
            [name]: val
        })
    }
    confirmEdit = () => {
        if (this.state.editName === undefined || this.state.editName === '') {
            message.error('请输入仓库名称！！！')
        } else if (this.state.editNum === undefined || this.state.editNum === '') {
            message.error('请输入仓库编号！！！')
        }
        else {
            // 向服务器发起请求存储修改的经销商,并判断名称和编号是否重复,返回哪个重复
            let obj = {
                repositoryAddress:this.state.editArea,
                repositoryCode:this.state.editNum,
                repositoryId:this.state.editId,
                repositoryName:this.state.editName,
            }
            axios({
                url:'/api' + url.updateRepository,
                method:'post',
                data:obj
            }).then(res=>{
                if(res.data.code == 200){
                    message.success('修改成功！')
                    this.getStoreData(1)
                }else{
                    message.error('修改失败！')
                }
            })
            this.setState({
                isShowEditStore: false,
                editLevel: '',
                editDiscount: '',
            })
        }

    }
    handleEditCancel = () => {
        this.setState({
            isShowEditStore: false

        })
    }
    // 设置默认
    setDefault = (id) => {
        let arr = JSON.parse(JSON.stringify(this.state.storeData))
        for (let i = 0; i < arr.length; i++) {
            arr[i].default = false;
            if (arr[i].repositoryId === id) {
                arr[i].default = true;
                let obj = arr[i]
                arr.splice(i, 1)
                arr.unshift(obj)
            }
        }
        // 向服务器发起请求

        this.setState({
            storeData: arr,
        })
        message.info('操作成功！！')
    }
    // 设置禁用
    setForbidden = (id) => {
        let arr = JSON.parse(JSON.stringify(this.state.storeData))
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].repositoryId === id) {
                let obj = arr[i]
                if (obj.flag) {
                    message.error('默认仓库不允许禁用！！')
                } else {
                    // 向服务器发起请求，判断该仓库是否有客户

                    let obj1 = {
                        repositoryId:obj.repositoryId
                    }
                    axios({
                        url:'/api' + url.judgeRepositoryHasClient,
                        method:'post',
                        data:obj1
                    }).then(res=>{
                        if(res.data.code === 200){
                            // 向服务器发起请求将改仓库状态改为禁用
                            let obj2 = {
                                repositoryId:obj.repositoryId,
                                repositoryStatus:1 -obj.repositoryStatus
                            }
                            console.log(obj2,'禁用传参！')
                            axios({
                                url:'/api'+url.prohibitRepository,
                                method:'post',
                                data:obj2,
                            }).then(res=>{
                                console.log(res,'禁用返回')
                                if(res.data.code === 200){
                                    message.success('操作成功！')
                                    this.getStoreData(1)
                                }else{
                                    message.error('操作失败！')
                                }
                            })

                        }else{
                            this.setState({
                                isShowForbiddenStore: true,
                                nowId: obj.repositoryId,
                                nowStore: obj.repositoryName,
                            })
                        }
                    })
                }

            }
        }
    }
    handleSelectChange = (value) => {
        let arr = JSON.parse(JSON.stringify(this.state.storeData))
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].repositoryId === value) {
                this.setState({
                    forbiddenNeedData: {
                        original: this.state.nowId,
                        target: arr[i].id,
                    }
                })
            }
        }
    }
    confirmForbidden = () => {
        console.log(this.state.deleteNeedData, 6565)
        if (this.state.forbiddenNeedData === undefined) {
            message.error('请选则仓库！！')
        } else {
            // 向服务器发起请求
            this.setState({
                isShowForbiddenStore: false
            })
        }

    }
    handleForbiddenCancel = () => {
        this.setState({
            isShowForbiddenStore: false
        })
    }
    // 删除仓库
    deleteStore = (id) => {
        let arr = JSON.parse(JSON.stringify(this.state.storeData))
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].repositoryId === id) {
                let obj = arr[i]
                if (obj.flag) {
                    message.error('默认仓库不允许禁用！！')
                } else {
                    let that = this
                    confirm({
                        title: '删除的仓库不能恢复，确认删除?',
                        icon: <ExclamationCircleOutlined />,
                        // content: 'Some descriptions',
                        okText: '确定',
                        okType: 'danger',
                        cancelText: '取消',
                        onOk() {
                             // 向服务器发起请求，判断该仓库是否有客户
                            let obj1 = {
                                repositoryId:obj.repositoryId
                            }
                            axios({
                                url:'/api' + url.judgeRepositoryHasClient,
                                method:'post',
                                data:obj1
                            }).then(res=>{
                                if(res.data.code === 200){
                                    // 向服务器发起请求将改仓库删除
                                    let obj2 = {
                                        repositoryId:obj.repositoryId
                                    }
                                    axios({
                                        url:'/api'+url.delRepository,
                                        method:'post',
                                        data:obj2,
                                    }).then(res=>{
                                        console.log(res,'删除')
                                        if(res.data.code === 200){
                                            message.success('删除成功！')
                                            that.getStoreData(1)
                                        }else{
                                            message.error('删除失败！')
                                        }
                                    })

                                }else{
                                    message.error('仓库删除失败，客户默认发货仓库引用了此仓库，不能删除！')
                                }
                            })
                    
                            
                        },
                        // onCancel() {
                        //   console.log('Cancel');
                        // },
                    });
                }

            }
        }
    }
    // 新增
    showNewStoreModule = () => {
        this.setState({
            isShowNewStore: true
        })
    }
    handelNewChange = (e) => {
        let val = e.target.value.replace(/\s+/g, "")//获取属性值
        let name = e.target.name//获取表单元素的name属性
        this.setState({
            [name]: val
        })
    }
    confirmNew = () => {
        let reg = new RegExp(/[0-9A-Za-z]{1,20}/)
        if (this.state.name === undefined || this.state.name === '') {
            message.error('请输入仓库名称！！！')
        } else if (this.state.num === undefined || this.state.num === '') {
            message.error('请输入仓库编号！！！')
        }else if(!reg.test(this.state.num)){
            message.error('仓库编码为20位以内的字母或数字！')
        }
        else {
            // 向服务器发起请求存储仓库信息，并判断仓库名称和编号是否重复，并返回哪个重复
            let obj = {
                repositoryName:this.state.name,
                repositoryCode:this.state.num,
                repositoryAddress:this.state.area,
            }
            axios({
                url:'/api'+url.addRepository,
                method:'post',
                data:obj
            }).then(res=>{
                console.log(res)
                if(res.data.code === 200){
                    message.success('新增成功！')
                    this.getStoreData(1)
                }else{
                    message.error('新增失败！')
                }
            })
            this.setState({
                isShowNewStore: false,
                name: '',
                num: '',
                area:'',
            })
        }

    }
    handleNewCancel = () => {
        this.setState({
            isShowNewStore: false
        })
    }
    render() {
        return (
            <div className={storeHouse.content}>
                <Row className={storeHouse.newBox}>
                    <Col span={24}>
                        <Button type="primary" className={storeHouse.newBtn}
                            onClick={this.showNewStoreModule}>新增</Button>
                    </Col>
                </Row>
                <Table rowKey = 'repositoryId' dataSource={this.state.storeData?this.state.storeData:[]} columns={this.state.columns} pagination={this.state.pagination?this.state.pagination:{}} />
                <Modal
                    title="新增仓库"
                    visible={this.state.isShowNewStore}
                    onOk={this.confirmNew}
                    cancelText={'取消'}
                    okText={'确定'}
                    onCancel={this.handleNewCancel}
                >
                    <div className={storeHouse.inputBox}>
                        <span className={storeHouse.newTips}> <span>*</span>仓库名称</span>
                        <Input className={storeHouse.newStore} name='name'
                            value={this.state.name} onChange={this.handelNewChange} />
                    </div>
                    <div className={storeHouse.inputBox}>
                        <span className={storeHouse.newTips}> <span>*</span>仓库编码</span>
                        <Input className={storeHouse.newStore} name='num'
                            value={this.state.num} onChange={this.handelNewChange} />
                    </div>
                    <div className={storeHouse.inputBox}>
                        <span className={storeHouse.newTips}>仓库地址</span>
                        <Input className={storeHouse.newStore} name='area'
                            value={this.state.area} onChange={this.handelNewChange} />
                    </div>
                </Modal>
            </div>
        )
    }
}
